package com.demo.webapp.kcfinder.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.common.StringUtils;
import com.demo.webapp.kcfinder.Dispatcher;
import com.demo.webapp.kcfinder.KCFinderStatics;

/**
 * KCFinder监听器
 * 容器启动时加载必要的配置文件信息
 * @author ryuu.kk
 *
 */
public class KCFinderListener implements ServletContextListener {

	private static final Log Logger = LogFactory.getLog(KCFinderListener.class);
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// create dispatcher
		Dispatcher dispatcher = new Dispatcher(sce.getServletContext());
		// get configuration file path from web.xml
		String configPath = sce.getServletContext().getInitParameter(KCFinderStatics.SERVLET_CONFIGURATION_NAME);
		if (StringUtils.isEmpty(configPath)) {
			if (Logger.isDebugEnabled()) {
				Logger.debug("not found location config,use a default configuration file");
			}
		} else {
			//使用本地Action映射文件
			dispatcher.setConfigurationPath(configPath);
		}
		String propertiesPath = sce.getServletContext().getInitParameter(KCFinderStatics.SERVLET_PROPERTIES_NAME);
		if (StringUtils.isEmpty(configPath)) {
			if (Logger.isDebugEnabled()) {
				Logger.debug("not found location config,use a default configuration file");
			}
		} else {
			//使用本地属性配置文件
			dispatcher.setPropertiesPath(propertiesPath);
		}
		
		dispatcher.init();
		//save to ServletContext
		sce.getServletContext().setAttribute(KCFinderStatics.SERVLET_DISPATCHER, dispatcher);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// 销毁实例对象
		Dispatcher.setInstance(null);
	}
}
